// import $ from './lib/jquery';
import React from 'react';
import { render } from 'react-dom';
import Header from './component/header';
import Bodyer from './component/bodyer';
import Sidebar from './component/sidebar';
import Modaler from './component/modal';
import DBConfig from './component/modals/dbconfig';
import DBdata from './component/modals/dbdata';
import Tpler from './component/modals/tpls';
import NewTpler from './component/modals/newtpl';
import FileConf from './component/modals/file';


import Hooks from './common/hooks';
import tools from './common/tools';

const opts={
      table:'.table-warp',
      tabs:'.tabs-warper',
      tabsitem:'.tabs-item',
      tabsidprefix:'tabs-',
      addtabs:'.new-table-btn',
      statusview:'.active-cont',
      formuladel:'.formula-del',
      formulasave:'.formula-save',
      formulaval:'#formula-val',
      scalebtn:'.cmd-scale',
      stylesbtn:'.styles-item',
      viewscalecont:'.view-scale-cont',
      widgetBox:'.htBorders',
      savebtn:'#save-btn'
}

class UI {
    constructor(host,marker){
        var that=this;
        this.marker=marker;
        this.host=host;
        this.hooks=new Hooks();
        // 通用模态提示窗口
        this.modalcontrol=new Hooks();
        this.modalcontrol.addHook('callback',function(data){
            console.log(data);
        });
        
        // 数据库配置模态窗口
        this.dbconfcontrol=new Hooks();
        this.dbconfcontrol.addHook('callback',function(data){
            console.log(data);
        });

        this.dbdatacontrol=new Hooks();
        this.dbdatacontrol.addHook('callback',function(data){
            // console.log('dbdata',data.params);
            let result=data.params;
            if(result.evt==='ok'){
                that.hooks.dispatch('opendatabase',result.data);
            }
        });

        this.tplercontrol=new Hooks();
        this.tplercontrol.addHook('callback',function(data){
            that.hooks.dispatch('opensheet',data.params);
        });

        this.newtplercontrol=new Hooks();
        this.newtplercontrol.addHook('callback',function(data){
            that.hooks.dispatch('newsheet',data.params);
        });

        this.fileconfcontrol=new Hooks();
        this.fileconfcontrol.addHook('callback',function(data){
            that.hooks.dispatch('updatefileconf',data.params);
            that.getFields(data.params.tpl_id);
        });

        this.sidebarcontrol=new Hooks();
        this.sidebarcontrol.addHook('callback',function(data){
            let params=data.params;
            that.hooks.dispatch('changeCellProps',{event:params.type,data:params.data});
        });

        this.bodyercontrol=new Hooks();
        this.bodyercontrol.addHook('callback',function(data){
            let params=data.params;
            that.hooks.dispatch('changeCellProps',{event:params.type,data:params.data});
        });
        
        // 初始化主界面
        this.initDom();
    }
    init(sheets){
  		this.initTabs(sheets);
  		this.bindEvent();
  	}
    initFields(fields){
        this.sidebarcontrol.dispatch('change',{fields:fields});
    }
    initDom(){
        let that=this;
        // 头部按钮回调
        let callback=function(evt){
            // console.log(evt);
            switch(evt){
                case 'new-tpl':
                    that.newtplercontrol.dispatch('show',null);
                break;
                case 'open-tpl':
                    that.tplercontrol.dispatch('show',{state:{usetype:0}});
                break;
                case 'save-tpl':
                    that.hooks.dispatch('savesheet',null);
                break;
                case 'tpl-db':
                    that.hooks.dispatch('todb',null);
                break;
                case 'use-tpl':
                    that.tplercontrol.dispatch('show',{state:{usetype:1}});
                break;
                case 'open-db':
                    that.dbdatacontrol.dispatch('show',null);
                break;
                case 'save-db':
                    // coding...
                    that.hooks.dispatch('savedata',null);
                break;
                case 'database-conf':
                    that.dbconfcontrol.dispatch('show',null);
                break;
                case 'file-conf':
                    that.hooks.dispatch('getfile',{evt:'file-conf'});
                break;
            };
            // that.hooks.dispatch('menucallback',evt);
        };
        let tableurl=that.host+'/TrueDPS/trueDataController/getModelList.do?callback=?';
        let tplsurl=that.host+'/TrueDPS/trueDataController/getTemplateList.do?callback=?';
        let tplurl=that.host+'/TrueDPS/trueDataController/getTemplate.do?callback=?&id=';
        let fieldurl=that.host+'/TrueDPS/trueDataController/getFieldList.do?modelId=';

        // 主UI
        render((
            <div className="app-warper">
                <Header callback={callback}/>
                <div className="app-container">
                    <Bodyer control={this.bodyercontrol}/>
                    <Sidebar control={this.sidebarcontrol}/>
                </div>
                <div id="loading"><i className="fa fa-lg fa-spin fa-spinner"></i><span></span></div>
                <Modaler control={this.modalcontrol}/>
                <DBConfig control={this.dbconfcontrol}/>
                <DBdata control={this.dbdatacontrol} source={tableurl}/>
                <Tpler control={this.tplercontrol} source={tplsurl} detailsource={tplurl}/>
                <NewTpler control={this.newtplercontrol} />
                <FileConf control={this.fileconfcontrol} />
            </div>
        ),document.querySelector('#app'));

        this.getTables();
    }
    sendfile(file,params){
        let that=this;
        switch(params.evt){
            case 'file-conf':
                that.fileconfcontrol.dispatch('show',{state:{
                    tpl_name:file.name||'',
                    tpl_enname:file.dbname||'',
                    tpl_type:file.type||'',
                    tpl_desc:file.desc||'',
                    tpl_state:file.state||0,
                    tpl_id:file.dbid||0
                }});
            break;
        }
    }
    getTables(){
        let that=this;
        $.getJSON(this.host+'/TrueDPS/trueDataController/getModelList.do?callback=?&t='+new Date().getTime(), function(result) {
            let tables=[{id:'null',name:'请选择',value:''}];
            if(result.error===null){
                result.data.forEach(e=>{
                    tables.push({id:e.modelId, name:e.tableDesc, value:e.tableName});
                });
            }
            that.fileconfcontrol.dispatch('change',{state:{tables:tables}});
        });
    }
    getFields(modelid){
        let that=this;
        $.getJSON(this.host+'/TrueDPS/trueDataController/getFieldList.do?modelId='+modelid+'&callback=?&t='+new Date().getTime(), function(result) {
            let fields=[{name:'',note:'请选择',type:''}];
            if(result.error===null){
                result.data.fields.forEach(e=>{
                    fields.push({name:e.name,note:e.note,type:e.type});
                });
            }
            that.sidebarcontrol.dispatch('change',{state:{fields:fields}});
        });
    }
  	bindEvent(){
  		var that=this;
  		//比例调整
        $(document).on('click', '.cmd-scale', function(event) {
            event.preventDefault();
            var scale=$(this).data('scale');
            $('body').find('.cmd-scale').removeClass('active');
            $(this).addClass('active');
            $('#view-scale').text((scale*100)+'%');
            that.setViewScale(scale);
        });

        //撤销
        $(document).on('click','.undo',function(event){
            event.preventDefault();
            that.hooks.dispatch('undo');
        });
        //重做
        $(document).on('click','.redo',function(event){
            event.preventDefault();
            that.hooks.dispatch('redo');
        });
        //添加表
        $(document).on('click','.new-table-btn',function(event){
            event.preventDefault();
            var name=prompt("请输入标签名称");
            if(!tools.trim(name)){
                alert('输入的信息不完整。');
                return;
            }
            var id=tools.uuid(),name=name||'new sheets';
            that.addTabsItem(id,name);
            that.getTabsItem(id);
            that.hooks.dispatch('addsheet',{id:id,name:name});
        });
        //选择表
        $(document).on('click','.tabs-item',function(event){
            event.preventDefault();
            var id=$(this).data('id');
            that.getTabsItem(id);
            that.hooks.dispatch('getsheet',{id:id});
        });
  	}
  	//设置画布比例
  	setViewScale(scale){
        $('#sheets-container').css({
            transform: 'scale('+scale+')'
        });
    }
    //添加事件
    addHook(n,fn){
    	this.hooks.addHook(n,fn);
    }
    //设置公式
    setFormula(s){
        this.bodyercontrol.dispatch('change',{state:{value:s}});
    }
    //初始化选项卡
    initTabs(sheets){
    	var that=this,active=null;
        this.clearTabsItem();
    	sheets.forEach(function(e,i){
    		if(i==0) active=e.id;
    		that.addTabsItem(e.id,e.name);
    	});
    	that.getTabsItem(active);
    }
    clearTabsItem(){
        $('#sheets-tabs').find('.tabs-item').remove();
    }
    removeTabsItem(id){
        var items=$('#sheets-tabs').find('.tabs-item').each(function(){
            var _id=$(this).data('id');
            if(id===_id) $(this).remove();
        });
    }
    //添加选项卡
    addTabsItem(id,name){
    	$('#sheets-tabs').append('<span data-id="'+id+'" class="tabs-item">'+name+'</span>');
    }
    getTabsItem(id){
        $('.tabs-item').each(function(){
            var _id=$(this).data('id');
            if(_id===id){
                $(this).addClass('active');
            }else{
                $(this).removeClass('active');
            }
        });
    }
    showSelectionCell(o){
    	$('#selectionCellStatus').text(tools.numToLabel(o.c+1)+(o.r+1));
    	var val='';
    	if(!!o.cell&&!!o.cell.value) val=o.cell.value;
    	if(!!o.cell&&!!o.cell.formula) val='='+o.cell.formula;
        this.setFormula(val);
        let styles={
				'font-weight':''
				,'font-style':''
				,'text-decoration':''
				,'text-align':''
				,'color':''
				,'background-color':''
			}
            ,dbopts={
				type:'',
				field:'',
				comment:'',
				value:''
			};
        if(o.cell!=null){
            styles=o.cell.styles;
            dbopts=o.cell.dbopts;
        }
        this.sidebarcontrol.dispatch('change',{state:{
            styles:styles,
            dbopts:dbopts
        }});
    }
}

export default UI;